package base.shiro.demo.config;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class ExecutorConfig {
    private static final Logger logger = LoggerFactory.getLogger(ExecutorConfig.class);

    /**
     * 在spring中注入了线程池asyncPromiseExecutor
     * 使用方法：在需要加入线程池的方法增加@Async("asyncPromiseExecutor")就行了
     * @return
     */
    @Bean(name = "asyncPromiseExecutor")
    public ThreadPoolTaskExecutor asyncPromiseExecutor(){
        logger.info("启动线程池 asyncPromiseExecutor");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //设置核心线程数
        executor.setCorePoolSize(10);
        //配置最大线程数
        executor.setMaxPoolSize(200);
        //配置队列大小
        executor.setQueueCapacity(10);
        //配置线程池中的线程名称前缀
        executor.setThreadNamePrefix("async-promise-");
        //pool 已经最大max值时，如何处理新任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //初始化容器
        executor.initialize();
        return executor;
    }
}
